<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>九宫格</title>
</head>
<body>
    <div class="box">
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
    </div>
    <div class="btn-box">
        <div onclick="start()">start</div>
        <div onclick="end()">end</div>
        <div onclick="reset()">reset</div>
    </div>
</body>
</html>
<style>
    .box{
        width: 200px;
        height: 200px;
        background-color: rgb(88, 88, 86);
        margin: auto;
        display: flex;
        flex-wrap: wrap;
    }
    .box .item {
        width: 30%;
        height: 30%;
        margin: 1.65%;
        border-radius: 5px;
        background-color: rgb(238, 226, 66);
    }
    .btn-box{
        margin: auto;
        width: 200px;
        text-align: center;
    }
     .btn-box div{
        background-color: rgb(173, 111, 16);
        margin: 5px auto;
        width: 50px;
        border-radius: 5px;
        color: #fff;
    }
</style>
<script>
    let setintvalkey = ''

    function start(e){
        setintvalkey =  setInterval("change()",1000)
    }
    function end(e){
        clearInterval(setintvalkey)
    }
    function reset(e){
        var x = document.querySelectorAll(".item");
        for(let i = 0;i<x.length; i++){
            x[i].style.backgroundColor = "rgb(238, 226, 66)";
        }
    }
    function change(){
        let num = random() //获取要变的灯数
        var x = document.querySelectorAll(".item");
        for(let i = 0;i<x.length; i++){
            x[i].style.backgroundColor = "rgb(238, 226, 66)";
        }
        for(let i = 0;i<num; i++){
            let xkey = random()
            console.log('xkey',xkey);
            x[xkey].style.backgroundColor = getRandomColor();
        }
    }
    function random(){
        return Math.floor(Math.random()*9);
    }
    var getRandomColor = function(){
        return '#'+Math.floor(Math.random()*16777215).toString(16);
    }
</script>